package com.wang.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.exception.BusinessException;
import com.wang.reponse.ChatMessageVo;
import com.wang.reponse.ChatSessionVo;
import com.wang.reponse.UserVo;
import com.wang.user.mapper.ChatMessageMapper;
import com.wang.user.mapper.ChatSessionMapper;
import com.wang.user.model.ChatMessage;
import com.wang.user.model.ChatSession;
import com.wang.user.model.User;
import com.wang.user.service.ChatService;
import com.wang.user.service.user.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 聊天服务实现类
 */
@Service
public class ChatServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage>
        implements ChatService {

    @Resource
    private UserService userService;

    @Resource
    private ChatSessionMapper chatSessionMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean sendMessage(ChatMessage message) {
        // 获取当前登录用户
//        User loginUser = userService.getLoginUser();
        message.setSenderId(5);
        message.setStatus(0); // 设置消息为未读状态

        // 保存消息
        boolean success = save(message);
        if (!success) {
            throw new BusinessException("发送消息失败");
        }

        // 更新或创建会话
        updateOrCreateSession(message);

        return true;
    }

    @Override
    public List<ChatMessageVo> getChatHistory(Integer targetId) {
        // 获取当前登录用户
        User loginUser = userService.getLoginUser();
        
        // 获取聊天记录
        List<ChatMessage> messages = baseMapper.getChatHistory(loginUser.getUid(), targetId);
        // 获取相关用户信息
        List<Integer> userIds = messages.stream()
                .flatMap(msg -> Stream.of(msg.getSenderId(), msg.getReceiverId()))
                .distinct()
                .collect(Collectors.toList());
        List<User> users = userService.listByIds(userIds);
        Map<Integer, User> userMap = users.stream()
                .collect(Collectors.toMap(User::getUid, u -> u));

        // 转换为VO
        return messages.stream().map(message -> {
            ChatMessageVo vo = new ChatMessageVo();
            BeanUtils.copyProperties(message, vo);
            
            // 设置发送者信息
            User sender = userMap.get(message.getSenderId());
            if (sender != null) {
                UserVo senderVo = new UserVo();
                BeanUtils.copyProperties(sender, senderVo);
                vo.setSender(senderVo);
            }
            
            // 设置接收者信息
            User receiver = userMap.get(message.getReceiverId());
            if (receiver != null) {
                UserVo receiverVo = new UserVo();
                BeanUtils.copyProperties(receiver, receiverVo);
                vo.setReceiver(receiverVo);
            }
            
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<ChatSessionVo> getSessionList() {
        // 获取当前登录用户
        User loginUser = userService.getLoginUser();
        
        // 获取会话列表
        List<ChatSession> sessions = chatSessionMapper.getSessionList(loginUser.getUid());
        
        // 获取相关用户信息
        List<Integer> targetIds = sessions.stream()
                .map(ChatSession::getTargetId)
                .collect(Collectors.toList());
        List<User> users = userService.listByIds(targetIds);
        Map<Integer, User> userMap = users.stream()
                .collect(Collectors.toMap(User::getUid, u -> u));

        // 转换为VO
        return sessions.stream().map(session -> {
            ChatSessionVo vo = new ChatSessionVo();
            BeanUtils.copyProperties(session, vo);
            
            // 设置目标用户信息
            User targetUser = userMap.get(session.getTargetId());
            if (targetUser != null) {
                UserVo targetUserVo = new UserVo();
                BeanUtils.copyProperties(targetUser, targetUserVo);
                vo.setTargetUser(targetUserVo);
            }
            
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean markAsRead(Integer targetId) {
        // 获取当前登录用户
        User loginUser = userService.getLoginUser();
        
        // 更新消息状态
        LambdaQueryWrapper<ChatMessage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatMessage::getSenderId, targetId)
                .eq(ChatMessage::getReceiverId, loginUser.getUid())
                .eq(ChatMessage::getStatus, 0);
        
        ChatMessage updateMessage = new ChatMessage();
        updateMessage.setStatus(1);
        
        boolean success = update(updateMessage, wrapper);
        if (!success) {
            throw new BusinessException("标记已读失败");
        }

        // 更新会话未读数
        ChatSession session = chatSessionMapper.getSession(loginUser.getUid(), targetId);
        if (session != null) {
            session.setUnreadNum(0);
            chatSessionMapper.updateById(session);
        }

        return true;
    }

    @Override
    public Integer getUnreadCount() {
        // 获取当前登录用户
        User loginUser = userService.getLoginUser();
        return baseMapper.getUnreadCount(loginUser.getUid());
    }

    /**
     * 更新或创建会话
     */
    private void updateOrCreateSession(ChatMessage message) {
        // 获取或创建发送者的会话
        ChatSession senderSession = chatSessionMapper.getSession(message.getSenderId(), message.getReceiverId());
        if (senderSession == null) {
            senderSession = new ChatSession();
            senderSession.setUserId(message.getSenderId());
            senderSession.setTargetId(message.getReceiverId());
            senderSession.setUnreadNum(0);
            chatSessionMapper.insert(senderSession);
        } else {
            senderSession.setLastMsg(message.getContent());
            chatSessionMapper.updateById(senderSession);
        }

        // 获取或创建接收者的会话
        ChatSession receiverSession = chatSessionMapper.getSession(message.getReceiverId(), message.getSenderId());
        if (receiverSession == null) {
            receiverSession = new ChatSession();
            receiverSession.setUserId(message.getReceiverId());
            receiverSession.setTargetId(message.getSenderId());
            receiverSession.setUnreadNum(1);
            chatSessionMapper.insert(receiverSession);
        } else {
            receiverSession.setUnreadNum(receiverSession.getUnreadNum() + 1);
            receiverSession.setLastMsg(message.getContent());
            chatSessionMapper.updateById(receiverSession);
        }
    }
} 